package com.mzy.concurrent;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class ThreadPrintExample {

    private static int currentNum = 1;
    private static int currentThread = 0;  // 用于标记哪个线程应该执行
    private static final Lock lock = new ReentrantLock();
    private static final Condition[] conditions = new Condition[3];  // 创建3个Condition对象

    public static void main(String[] args) {
        // 初始化Condition对象
        for (int i = 0; i < 3; i++) {
            conditions[i] = lock.newCondition();
        }

        // 创建三个线程
        Thread t1 = new Thread(new PrintTask(0));
        Thread t2 = new Thread(new PrintTask(1));
        Thread t3 = new Thread(new PrintTask(2));

        // 启动线程
        t1.start();
        t2.start();
        t3.start();
    }

    static class PrintTask implements Runnable {
        private final int threadId;

        public PrintTask(int threadId) {
            this.threadId = threadId;
        }

        @Override
        public void run() {
            while (true) {
                lock.lock();
                try {
                    // 轮到当前线程打印时执行
                    while (threadId != currentThread) {
                        conditions[threadId].await();
                    }

                    // 打印当前数字并增加
                    if (currentNum <= 100) {
                        System.out.println("Thread-" + (threadId + 1) + ": " + currentNum++);
                    } else {
                        // 打印结束后唤醒其他线程并退出
                        conditions[(threadId + 1) % 3].signal();
                        break;
                    }

                    // 切换到下一个线程
                    currentThread = (currentThread + 1) % 3;
                    // 唤醒下一个线程
                    conditions[currentThread].signal();
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                } finally {
                    lock.unlock();
                }
            }
        }
    }
}
